#include "task_queue.h"
#include <stdio.h>
#include <stdlib.h>

TaskNode *
create_task (int task_id)
{
  TaskNode *new_task = (TaskNode *)malloc (sizeof (TaskNode));
  if (!new_task)
    {
      perror ("Memory allocation failed");
      exit (EXIT_FAILURE);
    }
  new_task->task_id = task_id;
  new_task->next = NULL;
  return new_task;
}

TaskNode *
reverse_task_queue_by_group (TaskNode *head, int k)
{
  int i = 0;
  TaskNode dummy = {
    .next = head,
  };
  TaskNode *front = head, *back = head, *lastTail = &dummy, *curTail, *tmp;
  while (back)
    {
      i = 0;
      curTail = front;
      while ((i < k) && (back != NULL))
        {
          tmp = back->next;
          back->next = front;
          front = back;
          back = tmp;
          i++;
        }
      lastTail->next = front;
      lastTail = curTail;
      front = back;
    }
  curTail->next = NULL;
  return dummy.next;
}

void
free_task_queue (TaskNode *head)
{
  TaskNode *current = head;
  TaskNode *temp;
  while (current != NULL)
    {
      temp = current;
      current = current->next;
      free (temp);
    }
}

void
print_task_queue (TaskNode *head)
{
  TaskNode *current = head;
  while (current != NULL)
    {
      printf ("%d ", current->task_id);
      current = current->next;
    }
  printf ("\n");
}
